package service.report.impl;

import hirondelle.date4j.DateTime;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.TimeZone;

import util.Time;
import java.util.Map;

import model.contract.Loaninterest;



import dao.CompanybasicDao;
import dao.LoangrantDao;
import dao.LoaninterestDao;
import dao.PersonalbasicDao;
import dao.TContractDao;

import service.report.ReportContractService;

public class ReportContractServiceImpl implements ReportContractService {
	private TContractDao contractDao;
	private LoangrantDao loangrantDao;
	private LoaninterestDao loaninterestDao;
	private PersonalbasicDao personalbasicDao;
	private CompanybasicDao companybasicDao;
	
	@SuppressWarnings("unchecked")
	@Override
	public List<Map<Object,Object>> getReportContractList(String time1) {
		StringBuffer select=new StringBuffer().append(" ( case  when tc.clienttype=2 then  ( select c.name from companybasic as c where c.id=tc.clientid limit 0,1) ")
					.append(" when tc.clienttype=1 then ( select p.name from personalbasic as p where p.id=tc.clientid limit 0,1)  ")
					.append(" else '0' end ) as customname , ")
					.append("DATE_FORMAT(lg.grantdate,'%Y-%m-%d') as grantdate,DATE_FORMAT(lg.refunddate,'%Y-%m-%d') as refunddate,")
					.append("lg.grantmoney, ")
					.append("lg.grantnum, ")
					.append("tc.performrates, ")
					.append("(TO_DAYS(enddate) - TO_DAYS(startdate)) as dd, ")
					.append("DATE_FORMAT( lg.repaydate,'%Y-%m-%d') as repaydate, ").append("lg.balance, ").append("lg.id, ")
					.append("tc.modeD , tc.modeZ , tc.modeB ,tc.modeX");
		
		StringBuffer from=new StringBuffer().append("t_contract as tc , loangrant as lg where tc.Id=lg.contractid and ( lg.state=0 or lg.state=2 or lg.state=3 )");
		if(!time1.equals(""))
			from.append(" and ( lg.grantdate between '"+time1+"' )");
		
		List<?> getList=contractDao.findSqlQuery(select.toString(),from.toString(),0);
		
		List<Map<Object,Object>> list=new ArrayList<Map<Object,Object>>();
		if(null!=getList){
			Map<Object,Object> mapbean = null;
			int listsize=getList.size();
			for(int i=0;i<listsize;i++){
				mapbean=(Map<Object, Object>)getList.get(i);				
				
				int loanid=(Integer)mapbean.get("id");
								
				Loaninterest lii=loaninterestDao.findByOne("loanid="+loanid+" and state=1 and ( begaindate <= curdate() and curdate() <= lastdate )");
				if(lii==null){
					mapbean.put("lastvaluedate", "");
					mapbean.put("valuedate", "");
					mapbean.put("days", "");
					mapbean.put("interests", 0);
				}else{
					DateTime nowMonth=DateTime.now(TimeZone.getDefault());
					
					//判断当前日期是否大于20号，大于则应从下个月计算利息日
					DateTime startOfMonth=null;
					if(nowMonth.getDay()>20){
						startOfMonth=nowMonth.plusDays(15).getStartOfMonth();
					}else{
						startOfMonth=nowMonth.getStartOfMonth();
					}					
					
					//上月计息日
					DateTime lastValueDate=startOfMonth.minus(0,1,0,0,0,0,0,DateTime.DayOverflow.FirstDay).getStartOfMonth().plusDays(19);
					//~~如果上个计息日小于放款日期，则上个计息日应为放款日期，但不显示
					DateTime contractStartDate=new DateTime(mapbean.get("grantdate").toString());

					if(lastValueDate.lt(contractStartDate)){
						lastValueDate=contractStartDate;
						mapbean.put("lastvaluedate","");
					}else{
						mapbean.put("lastvaluedate",lastValueDate.format("YYYY-MM-DD"));
					}	
					
					//本月计息日
					DateTime valueDate=startOfMonth.plusDays(19);
					
					//还款日
					Timestamp repaydatesql=(Timestamp)mapbean.get("repaydate");
					DateTime repayDate=null;
					if(repaydatesql!=null){
						repayDate=new DateTime(Time.Timestamp2TimeString(repaydatesql));
					}							
					
					//计算天数
					int days=0;
					if(repayDate!=null){
						if(repayDate.lt(valueDate)){
							mapbean.put("valuedate", "");
							days=lastValueDate.numDaysFrom(repayDate);
							days+=1;
						}else{
							mapbean.put("valuedate",valueDate.format("YYYY-MM-DD"));
							days=lastValueDate.numDaysFrom(valueDate);
							//days+=1;
						}
					}else{
						mapbean.put("valuedate",valueDate.format("YYYY-MM-DD"));
						days=lastValueDate.numDaysFrom(valueDate);
						
						DateTime contractEndDate=new DateTime(mapbean.get("refunddate").toString());
						if(valueDate.lt(contractEndDate)){
							//days+=1;
						}
					}				
					mapbean.put("days",days);
					
					//计算利息
					/*BigDecimal jishu=((BigDecimal) mapbean.get("applymoney")).setScale(2, BigDecimal.ROUND_HALF_UP);
					BigDecimal lilv=((BigDecimal)mapbean.get("performrates")).setScale(5, BigDecimal.ROUND_HALF_UP);
					BigDecimal m360=new BigDecimal(36000);
					BigDecimal lixi=new BigDecimal(10).multiply(jishu).multiply(lilv).divide(m360,5,BigDecimal.ROUND_HALF_UP).setScale(5, BigDecimal.ROUND_HALF_UP);
					*/
					
					mapbean.put("interests",lii.getGrantmoney());
					mapbean.put("paidin",lii.getBackmoney());
					mapbean.put("nopaidin",lii.getGrantmoney()-lii.getBackmoney());					
				}
				
				list.add(mapbean);
			}
		}
		return list; 
	}

	public TContractDao getContractDao() {
		return contractDao;
	}

	public void setContractDao(TContractDao contractDao) {
		this.contractDao = contractDao;
	}

	public LoangrantDao getLoangrantDao() {
		return loangrantDao;
	}

	public void setLoangrantDao(LoangrantDao loangrantDao) {
		this.loangrantDao = loangrantDao;
	}

	public LoaninterestDao getLoaninterestDao() {
		return loaninterestDao;
	}

	public void setLoaninterestDao(LoaninterestDao loaninterestDao) {
		this.loaninterestDao = loaninterestDao;
	}

	public PersonalbasicDao getPersonalbasicDao() {
		return personalbasicDao;
	}

	public void setPersonalbasicDao(PersonalbasicDao personalbasicDao) {
		this.personalbasicDao = personalbasicDao;
	}

	public CompanybasicDao getCompanybasicDao() {
		return companybasicDao;
	}

	public void setCompanybasicDao(CompanybasicDao companybasicDao) {
		this.companybasicDao = companybasicDao;
	}
	
}
